//
//  WangYiReqManager.m
//  xunjiefanyiruanjian
//
//  Created by 陈镇 on 2024/8/6.
//

#import "WangYiReqManager.h"

#import "SLGetUUID.h"
#define kWYApiBase @"https://openapi.youdao.com/api"


//#define KappKay @"5db5d2e50d0061e9"
//#define KAppSecret @"dgumfngQADNmHHsXNcHdX8hVb6Qz35x7"

#define KappKay @"37aba9998ec80b82"
#define KAppSecret @"F5sezNnNWnDBkgkfvrPdcPwTMbwItYcH"

static WangYiReqManager *_manager = nil;
@implementation WangYiReqManager


-(void)clearHistory{
    [self.globalCache removeObjectForKey:kChatList];
    [self.globalCache removeObjectForKey:kVoiceList];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearHistory" object:nil];
}
-(YYCache *)globalCache{
    if(!_globalCache){
        _globalCache = [[YYCache alloc] initWithName:kGlobalCache];
    }
    return _globalCache;
}


+(instancetype)shareMangager{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [WangYiReqManager new];
    });
    return _manager;
}
#pragma mark -  文字翻译
-(void)requestPostfrom:(NSString *)from to:(NSString *)to query:(NSString *)query callBack:(SLRequestCallBack)callBack{
    
    
    query = [query stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    if(query.length == 0){
        return;
    }
    
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    
    NSString *input = query;
    if (query.length >=20) {
        
        input = [NSString stringWithFormat:@"%@%@%@",[query substringToIndex:10],@(query.length),[query substringFromIndex:query.length - 10]];
        
        RTLog(@"-----  %@",input );
        RTLog(@" [input sha256String] - %@ ", [input sha256String]);
    }
    
    NSInteger time = [NSDate new].timeIntervalSince1970;
    NSString *sign = [NSString stringWithFormat:@"%@%@%@%@%@",KappKay,input,[SLGetUUID UUID],@(time),KAppSecret];
    
    [dic setObject:query forKey:@"q"];
    [dic setObject:from forKey:@"from"];
    [dic setObject:to forKey:@"to"];
 
    [dic setObject:KappKay forKey:@"appKey"];
    [dic  setObject:[SLGetUUID UUID] forKey:@"salt"];
    
    [dic setObject:[sign sha256String] forKey:@"sign"];
    [dic setObject:@"v3" forKey:@"signType"];


    [dic setObject:@(time).stringValue forKey:@"curtime"];
    [dic setObject:@"mp3" forKey:@"ext"];
    
    NSString *url = kWYApiBase;

    SLBaseRequest *req = [[SLBaseRequest alloc] init];
    req.path = url;
    req.method = YTKRequestMethodGET;
    req.parameters = dic;
    req.requestHeader = @{@"Content-Type":@"application/json;charset=utf-8"};
    req.requestSerializerType = YTKRequestSerializerTypeJSON;
    
    
    [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {

        RTLog(@"trans_result - %@",request);
        RTLog(@"trans_result - %@",request.responseJSONObject);
        //src 原文    dst译文
        
        NSString *errorCode = request.responseJSONObject[@"errorCode"];
        if ([errorCode isEqualToString:@"0"]) {
            NSString *query = request.responseJSONObject[@"query"];
            NSString *tSpeakUrl = request.responseJSONObject[@"tSpeakUrl"];
            NSString *speakUrl = request.responseJSONObject[@"speakUrl"];
            NSArray *translation = request.responseJSONObject[@"translation"];
            NSString *toString = @"";
            for (NSString *t in translation) {
                toString = [toString stringByAppendingString:t];
            }
            
            if (toString.length > 0) {
                NSMutableDictionary *result = [NSMutableDictionary dictionary];
                
                if (query.length > 0) {
                    [result setObject:query forKey:@"orString"];
                }
                if (tSpeakUrl.length > 0) {
                    [result setObject:tSpeakUrl forKey:@"tSpeakUrl"];
                }
                if (toString.length > 0) {
                    [result setObject:toString forKey:@"taString"];
                }
                if (speakUrl.length > 0) {
                    [result setObject:speakUrl forKey:@"speakUrl"];
                }

                callBack(request,result);
            }else{
                SLTipToWindow(@"翻译失败");
            }
            
        }else{
            SLTipToWindow(@"翻译失败");
        }
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        SLTipToWindow(@"翻译失败");
        callBack(request,nil);
    }];

}
#pragma mark -  图片翻译
-(void)requesImagetPostfrom:(NSString *)from to:(NSString *)to query:(NSString *)query callBack:(SLRequestCallBack)callBack{
    
    if(query.length == 0){
        return;
    }
    
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    
    NSString *input = query;
    if (query.length >20) {
        input = [NSString stringWithFormat:@"%@%@%@",[query substringToIndex:10],@(query.length),[query substringFromIndex:query.length - 10]];
    }
    
    NSInteger time = [NSDate new].timeIntervalSince1970;
    NSString *sign = [NSString stringWithFormat:@"%@%@%@%@%@",KappKay,input,[SLGetUUID UUID],@(time),KAppSecret];
    
    [dic setObject:@"1" forKey:@"type"];
    [dic setObject:query forKey:@"q"];
    [dic setObject:from forKey:@"from"];
    [dic setObject:to forKey:@"to"];
 
    [dic setObject:KappKay forKey:@"appKey"];
    [dic  setObject:[SLGetUUID UUID] forKey:@"salt"];
    
    [dic setObject:[sign sha256String] forKey:@"sign"];
    [dic setObject:@"v3" forKey:@"signType"];


    [dic setObject:@(time).stringValue forKey:@"curtime"];
    [dic setObject:@"mp3" forKey:@"ext"];
    
    

    
    NSString *url = @"https://openapi.youdao.com/ocrtransapi";

    SLBaseRequest *req = [[SLBaseRequest alloc] init];
    req.path = url;
    req.method = YTKRequestMethodPOST;
    req.parameters = dic;
    
    [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {

        RTLog(@"trans_result - %@",request);
        RTLog(@"trans_result - %@",request.responseJSONObject);
        //src 原文    dst译文
        
        NSString *errorCode = request.responseJSONObject[@"errorCode"];
        if ([errorCode isEqualToString:@"0"]) {

            NSArray *resRegions = request.responseJSONObject[@"resRegions"];
            
            NSString *orString = @"";
            NSString *taString = @"";
            
            for (NSDictionary *t in resRegions) {
                orString = [orString stringByAppendingFormat:@"%@\n",t[@"context"]];
                taString = [taString stringByAppendingFormat:@"%@\n",t[@"tranContent"]];
            }
            
            if (orString.length > 0) {
                NSMutableDictionary *result = [NSMutableDictionary dictionary];
                
                if (query.length > 0) {
                    [result setObject:[orString qmui_trim] forKey:@"orString"];
                }
//                if (tSpeakUrl.length > 0) {
//                    [result setObject:tSpeakUrl forKey:@"tSpeakUrl"];
//                }
                if (taString.length > 0) {
                    [result setObject:[taString qmui_trim] forKey:@"taString"];
                }
//                if (speakUrl.length > 0) {
//                    [result setObject:speakUrl forKey:@"speakUrl"];
//                }

                callBack(request,result);
              
            }else{
                SLTipToWindow(@"翻译失败");
            }
            
        }else{
            SLTipToWindow(@"翻译失败");
        }
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        SLTipToWindow(@"翻译失败");
        callBack(request,nil);
    }];
}
#pragma mark -  语音翻译
-(void)requesVoicePostfrom:(NSString *)from to:(NSString *)to query:(NSString *)query callBack:(SLRequestCallBack)callBack{
    
    
    if(query.length == 0){
        return;
    }
    
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    
    NSString *input = query;
    if (query.length >20) {
        input = [NSString stringWithFormat:@"%@%@%@",[query substringToIndex:10],@(query.length),[query substringFromIndex:query.length - 10]];
    }
    
    NSInteger time = [NSDate new].timeIntervalSince1970;
    NSString *sign = [NSString stringWithFormat:@"%@%@%@%@%@",KappKay,input,[SLGetUUID UUID],@(time),KAppSecret];
    
    [dic setObject:@"1" forKey:@"type"];
    [dic setObject:query forKey:@"q"];
    [dic setObject:from forKey:@"from"];
    [dic setObject:to forKey:@"to"];
 
    [dic setObject:KappKay forKey:@"appKey"];
    [dic  setObject:[SLGetUUID UUID] forKey:@"salt"];
    
    [dic setObject:[sign sha256String] forKey:@"sign"];
    [dic setObject:@"v3" forKey:@"signType"];


    [dic setObject:@(time).stringValue forKey:@"curtime"];
    [dic setObject:@"mp3" forKey:@"ext"];
    
    [dic setObject:@"wav" forKey:@"format"];
    [dic setObject:@"16000" forKey:@"rate"];
    [dic setObject:@"1" forKey:@"channel"];

    
    NSString *url = @"https://openapi.youdao.com/speechtransapi";

    SLBaseRequest *req = [[SLBaseRequest alloc] init];
    req.path = url;
    req.method = YTKRequestMethodPOST;
    req.parameters = dic;
    
    [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {

        RTLog(@"trans_result - %@",request);
        RTLog(@"trans_result - %@",request.responseJSONObject);
        //src 原文    dst译文
        
        NSString *errorCode = request.responseJSONObject[@"errorCode"];
        if ([errorCode isEqualToString:@"0"]) {

            NSArray *resRegions = request.responseJSONObject[@"translation"];
            NSString *toString = @"";
            for (NSString *t in resRegions) {
                toString = [toString stringByAppendingFormat:@"%@\n",t];
            }
            
            if (toString.length > 0) {
                
                NSString *or_text = [request.responseJSONObject stringValueForKey:@"query" default:@""];
                
                NSString *tSpeakUrl = request.responseJSONObject[@"tSpeakUrl"];
                NSString *speakUrl = request.responseJSONObject[@"speakUrl"];
                
                NSDictionary *result = @{@"orString":or_text,
                                         @"taString":toString,
                                         @"tSpeakUrl":tSpeakUrl,
                                         @"speakUrl":speakUrl,
                                         
                };
                callBack(request,result);
            }else{
                SLTipToWindow(@"翻译失败");
            }
            
        }else{
            SLTipToWindow(@"翻译失败");
        }
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        SLTipToWindow(@"翻译失败");
        callBack(request,nil);
    }];
    
}
@end
